package com.yi.yier.boot.autoconfigure.codegenerator.api.exception.code;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 错误码定义
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-06-28 22:11
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-06-28
 * @modify reason: {方法名}:{原因}
 * ...
 */
@AllArgsConstructor
@Getter
public enum ApiErrorCode implements IErrorCode {
    /**
     * 失败
     */
    FAILED(0x00000001),
    /**
     * 系统异常
     */
    SYSTEM_ERROR(0x00000002),
    /**
     * 条件校验失败
     */
    CONDITION_NOT_SATISFY_ERROR(0x00000003),
    /**
     * 内部逻辑异常
     */
    INNER_LOGIC_ERROR(0x00000004),
    /**
     * 数据不存在
     */
    DB_NOT_EXIST_ERROR(0x00000005),
    /**
     * 成功
     */
    SUCCESS(0x00000000);

    private final Integer code;

    /**
     * code 载体
     * @param code
     * @return
     */
    public static IErrorCode valueOfCode(Integer code) {
        List<ApiErrorCode> codes = ListUtils.emptyIfNull(Arrays.stream(ApiErrorCode.values()).filter(p -> p.getCode().equals(code)).collect(Collectors.toList()));
        if (CollectionUtils.isNotEmpty(codes)) {
            return codes.get(0);
        }
        return RefErrorCode.builder().code(code).build();
    }

    /**
     * 错误编码
     */
    @Override
    public String getErrorCode() {
        return toHex(getCode());
    }

    /**
     * 多语言key
     *
     * @return
     */
    @Override
    public String getLanguageKey() {
        if (Objects.equals(SUCCESS.getCode(), code)) {
            return "success";
        }
        return "error." + getErrorCode() + ".description";
    }

}
